package br.com.projeco.persistencia.datastore;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import com.google.appengine.api.datastore.Key;
@SuppressWarnings("unchecked")
public class DBLibHelper {
	public static <T> T salvar(T objeto){		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		tx.begin();
		try {
			pm.makePersistent(objeto);
			tx.commit();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			if (tx.isActive())
		    {
		        // Error occurred so rollback the transaction
		        tx.rollback();
		    }
			pm.close();						
		}
		
		return objeto;
	}
	
	public static <T> List<T> consultar(Class<T> classe, String filtro){		
		List<T> resultado = new ArrayList<T>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(classe, filtro);
		resultado = (List<T>) query.execute();			
		pm.close();

		return resultado;
	}
	
	public static <T> T receber(Class<T> classe, Key key){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		T objeto = null;
		try {
			objeto = (T) pm.getObjectById(classe, key);	
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			pm.close();
		}

		return objeto;
	}
		
	public static <T> T receber(Class<T> classe, String codigo){		
		PersistenceManager pm = PMF.get().getPersistenceManager();	
		T objeto = null;
		try {
			objeto = (T) pm.getObjectById(classe, codigo);	
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			pm.close();
		}

		return objeto;
	}
	
	public static <T> void remover(T objeto){		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.deletePersistent(objeto);			
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			pm.close();
		}
	}
	
	public static <T> void remover(Class<T> classe, Key key){		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {			
			pm.deletePersistent((T) pm.getObjectById(classe, key));			
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			pm.close();
		}
	}	
	
	public static <T> void remover(Class<T> classe, String codigo){		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {			
			pm.deletePersistent((T) pm.getObjectById(classe, codigo));			
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			pm.close();
		}
	}		
}
